package xyz.zhzby.cyzx.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.stereotype.Service;
import xyz.zhzby.cyzx.oss.service.OssService;
import xyz.zhzby.cyzx.oss.util.ConstantYamlUtils;
import xyz.zhzby.cyzx.servicebase.domain.RestResponse;
import xyz.zhzby.cyzx.servicebase.exception.BusinessException;

import java.io.InputStream;
import java.util.UUID;

/**
 * @author zby
 * @date 2021/12/15
 */
@Service
public class OssServiceImpl implements OssService {

    @Override
    public RestResponse<String> uploadFileImg(InputStream inputStream, String folder) {
        String endpoint = ConstantYamlUtils.END_POIND;
        String accessKeyId = ConstantYamlUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantYamlUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantYamlUtils.BUCKET_NAME;

        try {
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String fileName = folder + "/" + uuid + ".png";
            ossClient.putObject(bucketName, fileName, inputStream);
            ossClient.shutdown();

            String url = "https://" + bucketName + "." + endpoint + "/" + fileName;
            return RestResponse.success(url);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("上传图片失败，请重试");
        }
    }

}
